package XMLread;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.StringTokenizer;

import database.MapDbAdapter;


import android.util.SparseArray;

/**
 * 
 * Parses a CSV file that contains definitions of spaces
 *
 */
public class ParseCSVspace {
	SparseArray<ArrayList<Space>> spacesByBuilding = new SparseArray<ArrayList<Space>>();

	/**
	 * Adds all spaces contained in csv file into database stored within the application
	 * @param sapceCSV the input stream obtained by opening the CSV file located in the assets folder
	 * @mapDbAdapter the database of this application
	 */
	public static void parse(InputStream spaceCSV, MapDbAdapter mapDbAdapter){

		//create BufferedReader to read csv file
		BufferedReader br;
		try {
			mapDbAdapter.open();
			br = new BufferedReader(new InputStreamReader(spaceCSV, "UTF-8"));

			String strLine = br.readLine();
			StringTokenizer st = null;
			
			//create each space and add it to hashMap accordingly
			while( (strLine = br.readLine()) != null)
			{
				//break comma separated line using ","
				st = new StringTokenizer(strLine, ",");
				String shape = st.nextToken();
				String buildingId = st.nextToken();
				String floor = st.nextToken();
				String room = st.nextToken();
				String roomLabel = st.nextToken();
				
				mapDbAdapter.addSpace(buildingId, room, roomLabel, floor, shape);				
			}
			
			mapDbAdapter.close();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
}
